package com.sofwin.service.impl;

import com.sofwin.dto.ResourceDto;
import com.sofwin.mapper.SysResourceMapper;
import com.sofwin.pojo.SysResource;
import com.sofwin.pojo.SysResourceExample;
import com.sofwin.service.ResourceService;
import io.swagger.annotations.Example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @packageName: com.sofwin.service.impl
 * @author: andyliu
 * @date: 2022/5/4 16:00
 * @email 115176513@qq.com
 * @description: TODO
 */
@Service
public class ResourceServiceImpl implements ResourceService {
    @Autowired
    private SysResourceMapper mapper;
    @Override
    public List<SysResource> queryResources(SysResource resource) {
        SysResourceExample example = new SysResourceExample();
        SysResourceExample.Criteria criteria = example.createCriteria();
        if(resource!=null){
            if(!StringUtils.isEmpty(resource.getResourceName())){
                criteria.andResourceNameLike("%"+resource.getResourceName()+"%");
            }
            if(resource.getStatus()!=null && resource.getStatus()!=-1){
                criteria.andStatusEqualTo(resource.getStatus());
            }
        }
        return mapper.selectByExample(example);
    }

    @Override
    public List<SysResource> queryResourceByRoleId(Integer roleId) {
        return mapper.selectResourceByRoleId(roleId);
    }

    @Override
    public SysResource queryById(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean saveOrUpdateResource(SysResource resource) {
        if(resource.getId()!=null){
            return mapper.updateByPrimaryKeySelective(resource)==1?true:false;
        }
        return mapper.insertSelective(resource)==1?true:false;
    }

    @Override
    public boolean removeById(Integer id) {
        return mapper.deleteByPrimaryKey(id)==1?true:false;
    }

    @Override
    public boolean removeByIds(Integer[] ids) {
        int flag =0;
        for(Integer id:ids){
            if(removeById(id)){
                flag++;
            }
        }
        return flag==ids.length?true:false;
    }

    @Override
    public List<ResourceDto> queryResourceByRoleIds(Integer roleId) {
        return mapper.selectRoleResources(roleId);
    }

    @Override
    public List<String> queryPermissionsByRoleId(Integer roleId) {
        return mapper.selectPermissions(roleId);
    }
}
